package com.lky.web.useradmin;

import com.lky.entity.User;
import com.lky.util.HttpServletRequestUtil;
import com.lky.util.ShiroUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RequestMapping(value="/useradmin")
public class UserLoginController {
    @RequestMapping(value="/loginuser")
    @ResponseBody
    public Map<String,Object> getUserListByName(HttpServletRequest request) {
        String username = HttpServletRequestUtil.getString(request, "username");
        String password = HttpServletRequestUtil.getString(request,"password");
        Map<String, Object> modelMap = new HashMap<String, Object>();
        if(null == username || null == password){
            modelMap.put("success",false);
            modelMap.put("errMsg","参数为空");
            return modelMap;
        }

        try {
            //代表当前用户
            Subject currentUser = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);

            currentUser.login(token);
            Subject subject = SecurityUtils.getSubject();
            String sessionId = (String) subject.getSession().getId();

            User user = ShiroUtil.getActiveUser();
            modelMap.put("success",true);
           // modelMap.put("errMsg","参数为空");

            return modelMap;
        }catch (Exception e){
            if(e.getClass().getName() != null){
                if(UnknownAccountException.class.getName().equals(e.getClass().getName())){
                    modelMap.put("success",false);
                    modelMap.put("errMsg","账号不存在");
                }else if (IncorrectCredentialsException.class.getName().equals(e.getClass().getName())){
                    modelMap.put("success",false);
                    modelMap.put("errMsg","用户名密码错误");
                }else{
                    //密码错误
                    //throw new CustomException("未知错误异常");
                    modelMap.put("success",false);
                    modelMap.put("errMsg","未知错误");
                }
            }
            return modelMap;
        }
    }

}
